import axios from "axios";

import type {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosRequestHeaders,
  AxiosResponse,
  AxiosError,
} from "axios";
axios.defaults.withCredentials = true;

class NetWork {
  instance: AxiosInstance;
  constructor() {
    this.instance = axios.create();

    this.instance.interceptors.request.use(
      (config) => {
        config.withCredentials = true;

        return config;
      },
      (error: AxiosError) => {
        Promise.reject(error);
      },
    );

    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        const dataAxios = response.data;
        const { code } = dataAxios;
        switch (code) {
          case 0:
            return dataAxios.data;
          case 1002:
            return;

          default:
            return Promise.reject(dataAxios.msg);
        }
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      },
    );
  }
}

export default new NetWork().instance;
